﻿# encoding: UTF-8
from strategy_platform.api import (submit_order,query_order,cancel_order, query_position,query_commodity_info,query_credit_fund_info)
from strategy_platform.api import (stop_strategy_framework, get_trade_days)
import datetime, pandas, numpy
import util

def get_cash_(): # must return two positives
	try:
		account = query_credit_fund_info(g['acct_type'], g['acct'])
		if account is None:
			log.error("query_my_acct: can not find the credit account")  
		log.info("credit info is : 现金:{}, 股票市值:{}, 担保资产:{}, 融资可用额度:{}, totalDebit:{}".format(account.fundAsset,account.marketValue,account.assureAsset,account.finEnableQuota,account.totalDebit))  
		return account.fundAsset, account.totalDebit, account.marketValue
	except Exception as e:   
		log.exception(e)


def on_init(argument_dict):
	global g
	g = {}
	g['acct_type']   = "C" #"SHHTSC"
	g['acct']        = "8009180103"	#"2497312" #
	for k, v in argument_dict.items():
		g[k] = v
	log.info(g)
	
	trade_date  = int(datetime.date.today().strftime('%Y%m%d'))
	yesterday   = util.get_prev_bizday(trade_date)
	log.info('yesterday=%d, trade_date=%d'%(yesterday, trade_date))
	
	#target = read_csv_('D:/prod/sk001/底仓.csv') #dataframe: code, qty
	#target.columns = ['code', 'targetqty']
	
	currpos = []
	pos_list = query_position(g['acct_type'], g['acct'])
	if pos_list != None:
		for pos_obj in pos_list:
			currpos.append({'code': pos_obj.symbol, 'currpos':  pos_obj.currentQty})
		currpos = pandas.DataFrame(currpos) #code, currqty
	#log.info(target.head(2))
	#log.info(eod.head(2))
		
	# cash, debit, stock = get_cash_(acct_type, acctno)
	capital = 250e4 * 0.97 #cash + debit +stock, need to check debit is positive or negative
	target = util.gen_targetpos_sk001(capital) #code, w1000, price, targetpos
	eod    = util.get_eod('sk001', yesterday) #code, eodpos
		
	todo = pandas.merge(eod[['code', 'eodpos']], target[['code', 'targetpos']], on=['code'], how='outer') #code, eodqty, targetqty, currqty
	if len(currpos)>0:
		todo = pandas.merge(todo, currpos[['code', 'currpos']], on=['code'], how='outer')
	else:
		todo['currpos'] = 0
	todo = todo.fillna(0).set_index('code')
	todo['qty'] = todo.targetpos - todo.currpos #qty to be traded
	
	# impose T+1 restriction
	todo['qty'] = numpy.where(todo.qty>=0, todo.qty, numpy.maximum(todo.qty, -todo.eodpos))
	log.info('eod = %d, curr = %d, target = %d, todo = %d'%(len(eod), len(currpos), len(target), len(todo)))
	#log.info(todo[todo.qty>0].head(3))
	
	# impose 688 restriction
	todo = todo[todo.qty!=0].reset_index()
	todo['iskc'] = [a.startswith('688') for a in todo.code]
	todo['qty']  = numpy.where(todo.iskc, numpy.where(todo.qty>0, numpy.minimum(todo.qty, 200), todo.qty), todo.qty)
	
	# add columns haoxing needs. 
	todo = todo[['code', 'qty']]
	todo.insert(0, 'id', ['id%06d'%a for a in range(1, len(todo)+1)])
	todo.insert(1, 'account_type', g['acct_type'])
	todo.insert(2, 'account', g['acct'])
	todo['side'] = numpy.where(todo.qty>0, 1, 2)
	todo['qty']  = [int(a) for a in todo.qty.abs()]
	todo['dumb'] = 'algo'
	todo['dumb2'] = 'AlgoType=HX_SMARTVWAP;beginTime=130000;endTime=133000;limitUpDownTrading=false; maxRate=0.2;limitPrice=0;extraParam=remark:hx_fundA_001&splitAmount:6000&ordFreqLmt:249;'
	log.info(todo.drop('dumb2', axis=1).head(5))
	log.info('target: %d, eod: %d, need to buy %d stocks, sell %d stocks'%(len(target), len(eod), (todo.side==1).sum(), (todo.side==2).sum()))
	
	todo = todo[todo.side==2].head(50) # 建仓后应该是 sell only。 建仓期间可以观察 sell only 够不够快
	filename = 'D:/prod/sk001/扫单文件/%d_noon.csv'%trade_date
	todo.to_csv(filename, index=0, header=False)
	log.info('中午的扫单文件已保存在%s'%filename)
	
	
	
	#log.info(todo[todo.target!=todo.qty].head(5))
	#log.info(target[target.qty==0])
	#log.info(eod.head(5))
	#log.info(todo.head(5))
	#stop_strategy_framework()
	
	
		